package controllers

import (
	"day01/models"
	beego "github.com/beego/beego/v2/server/web"
)

type StocksController struct {
	beego.Controller
}
type Msg struct {
	Code int
	Msg  string
	Data interface{}
}

func (c *StocksController) Add() {
	name := c.GetString("name")
	sex := c.GetString("sex")
	ss := models.Stocks{
		Name: name,
		Sex:  sex,
	}
	err := models.DB.Debug().Create(&ss).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "添加失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "添加成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *StocksController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(models.Stocks{}, id).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "删除失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "删除成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *StocksController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	sex := c.GetString("sex")
	ss := models.Stocks{
		Id:   id,
		Name: name,
		Sex:  sex,
	}
	err := models.DB.Debug().Updates(&ss).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "修改失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "修改成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *StocksController) List() {
	var alloct []models.Stocks
	err := models.DB.Debug().Find(&alloct).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "查询失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "查询成功",
			Data: alloct,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
